package org.wanda.pv.controller.basic;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.framework.page.Pagination;
import org.wanda.pv.model.basic.*;
import org.wanda.pv.model.business.Mark;
import org.wanda.pv.model.hy.HyDrawing;
import org.wanda.pv.model.view.PointSearchView;
import org.wanda.pv.service.basic.PointService;
import org.wanda.pv.service.view.PointViewService;

import javax.servlet.http.HttpServletRequest;
import java.lang.System;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/basic/point")
public class PointController {
    private final Log log = LogFactory.getLog(this.getClass());
    @Autowired
    private PointService pointService;

    @Autowired
    private  PointViewService pointViewService;

    @Autowired
    private Dao dao;

    @RequestMapping("/hi")
    public String hi(){
        return "111";
    }




    @RequestMapping("/listBySpecId")
    public Object listBySpecId(HttpServletRequest request,Long specId, Long systemId){
        String projectFlowChildrenNodeId = (String) request.getSession().getAttribute("projectFlowChildrenNodeId");
        //如果不传系统id
        if (null == systemId){
            Specialty specialty = dao.fetch(Specialty.class,Cnd.where("id","=",specId));
            dao.fetchLinks(specialty,null);
            specialty.getPoints().forEach(point -> {
                dao.fetchLinks(point,null);
                List<Mark> marks= dao.query(Mark.class,Cnd.where("point_id","=",point.getId()).and("project_flow_children_node_id","=",projectFlowChildrenNodeId).and("delFlag","=",0));
                point.setMarks(marks);
                point.getMarks().forEach(mark -> {
                    dao.fetchLinks(mark,null);
                    mark.getTopics().forEach(topic -> {
                        dao.fetchLinks(topic,null);
                    });
                });
            });
            return Result.success("success",specialty.getPoints());
        }

        Cnd cnd=Cnd.where("delFlag", "=", false);
        List<Point> points  = pointService.query(cnd.and("systemId", "=", systemId));
        points.forEach(point -> {
            dao.fetchLinks(point,null);
            List<Mark> marks= dao.query(Mark.class,Cnd.where("point_id","=",point.getId()).and("project_flow_children_node_id","=",projectFlowChildrenNodeId).and("delFlag","=",0));
            point.setMarks(marks);
            point.getMarks().forEach(mark -> {
                dao.fetchLinks(mark,null);
                mark.getTopics().forEach(topic -> {
                    dao.fetchLinks(topic,null);
                });
            });
        });

        return Result.success("success",points);


    }

    @RequestMapping("/listBySystem")
    public Object listBySystem(HttpServletRequest request, Long systemId){
        String projectFlowChildrenNodeId = (String) request.getSession().getAttribute("projectFlowChildrenNodeId");
        Cnd cnd=Cnd.where("delFlag", "=", false);
        List<Point> points  = pointService.query(cnd.and("systemId", "=", systemId));
        points.forEach(point -> {
            dao.fetchLinks(point,null);
            List<Mark> marks=  point.getMarks().stream().filter(item->item.getProjectFlowChildrenNodeId().equals(projectFlowChildrenNodeId)).collect(Collectors.toList());
            marks.forEach(mark -> {
               dao.fetchLinks(mark,null);
                mark.getTopics().forEach(topic -> {
                    dao.fetchLinks(topic,null);
                });
            });
        });
        return Result.success("success",points);
    }


    @RequestMapping("/listByView")
    public Object list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                       String name,
                       String specialtyName,
                       String systemName,
                       String pointRoomName
    ){


        try {

            PointSearchView searchView = new PointSearchView();
            searchView.setName(name);
            searchView.setSpecialtyName(specialtyName);
            searchView.setSystemName(systemName);
            searchView.setPointRoomName(pointRoomName);
            Pagination pagination = pointViewService.listByView(pageNum, pageSize, searchView);
            return Result.success("success",pagination);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误!");
        }



    }

    @RequestMapping("/updateLocaction")
    public Object updateQuestionLocation(Long id,Integer newLocation){
        try {
            Point point=dao.fetch(Point.class,id);
            if(point.getId()!=null){
                pointService.updatePointLocation(newLocation,point);
            }else{
                return Result.error("fail","找不到题目！");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误");
        }
        return Result.success("success","排序修改成功！");
    }


    @RequestMapping("/queryById")
    public Object queryById(Long id){

        try{
            Point point = dao.fetch(Point.class, id);
            dao.fetchLinks(point,null);

            return Result.success("success",point);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误");
        }


    }




    @RequestMapping("/update")
    public Object update(Long id,
                         String name,
                         String number,
                         Long  topPointId,
                         Long[] pointRoomIds,

                         Long specialtyId,
                         Long pointClassId,
                         Long systemId){
        try{

            Long[] specialtyIds =specialtyId==null?null:new Long[] {specialtyId};

            pointService.update(id,
                    name,
                    number,
                    topPointId,
                    pointRoomIds,
                    specialtyIds,
                    pointClassId,
                    systemId);
            return Result.success("success","操作成功!");

        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","操作失败!服务器内部错误");
        }




    }

    /**
     *
     * @param name
     * @param pointRoomIds
     * @param specialtyId
     * @param pointClassId
     * @param systemId
     * @return
     */
    @RequestMapping("/add")
    public Object add(String name,
                      String number,
                      Long topPointId,
                      Long[] pointRoomIds,
                      Long specialtyId,
                      Long pointClassId,
                      Long systemId){
        try{

            Long[] specialtyIds =specialtyId==null?null:new Long[] {specialtyId};

            Point point = pointService.add(name,
                    number,
                    topPointId,
                    pointRoomIds,
                    specialtyIds,
                    pointClassId,
                    systemId);
            return Result.success("success",point);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","操作失败!服务器内部错误!");
        }

    }

    @RequestMapping("/del")
    public Object del(Long id){
        // 判断该题目是否能被删除
        try {
            pointService.del(id);
            return Result.success("success","操作成功!");
        } catch (Exception e) {
           log.error(e.getMessage(),e);
            return Result.error("fail","操作失败!服务器内部错误!");
        }

    }




}
